import React, { useState, useEffect } from "react";
import Crumbs from "../../components/crumbs/index";
import Icon, { PlusOutlined } from "@ant-design/icons";
import { leftIcon, SubIcon } from "./svg/svg";
import { Input, Button, Upload, Modal, notification } from "antd";
import { addItem } from "../../api/store";
import "./scss/addItem.scss";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

// 提示框
const openNotificationWithIcon = (type, msg) => {
  notification[type]({
    message: msg,
  });
};

const AddItem = (props) => {
  const [dataList, setDataList] = useState({
    name: "",
    title: "",
    sort: "",
    stock: "",
    suttle: "",
    brand: "",
    keyword: "",
    describes: "",
    price: "",
    points: "",
    number: "",
  });

  useEffect(() => {
    if (props.location.state) {
      let {
        brand,
        description: describes,
        integration: points,
        inventory: stock,
        key,
        keyword,
        name,
        price,
        sort,
        title,
        weight: suttle,
      } = props.location.state;
      let data = {
        name,
        title,
        sort,
        stock,
        suttle,
        brand,
        keyword: JSON.parse(keyword).join(","),
        describes,
        price,
        points,
        number: 0,
        key,
      };
      setDataList(data);
    }
  }, []);

  // 所有的图片地址
  const [imgList, setImgList] = useState([]);

  const [previewVisible, setpreviewVisible] = useState(false);
  const [previewImage, setpreviewImage] = useState("");
  const [previewTitle, setpreviewTitle] = useState("");
  const [fileList, setfileList] = useState([]);
  const [CrumbsList] = useState([
    {
      name: "积分商城",
    },
    {
      name: "商城列表",
      url: "/MallList",
    },
    {
      name: "添加商品",
      url: "/additem",
    },
  ]);

  let handleCancel = () => setpreviewVisible(false);

  let handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    setpreviewImage(file.url || file.preview);
    setpreviewVisible(true);
    setpreviewTitle(
      file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
    );
  };

  let handleChange = ({ fileList }) => setfileList(fileList);

  // 跳转到上一层页面
  let backUrl = () => {
    props.history.go(-1);
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传照片</div>
    </div>
  );

  // 输入框同步数据
  let changeData = (e) => {
    let key = e.target.name;
    let value = e.target.value;
    dataList[key] = value;
    setDataList(JSON.parse(JSON.stringify(dataList)));
  };

  // 同步图片地址
  useEffect(() => {
    setImgList(fileList.map((item) => item.response?.url));
  }, [fileList]);

  // 保存并上架
  let SubIconFun = (state) => {
    let axiosData = JSON.parse(JSON.stringify(dataList));
    let {
      name,
      title,
      sort,
      stock,
      suttle,
      brand,
      keyword,
      describes,
      price,
      points,
      number,
    } = axiosData;
    if (
      !name ||
      !title ||
      !sort ||
      !stock ||
      !suttle ||
      !brand ||
      !keyword ||
      !describes ||
      !price ||
      !points
    ) {
      openNotificationWithIcon("warning", "请填写完毕所有内容");
      return;
    }
    if (!imgList.length) {
      openNotificationWithIcon("warning", "最少上传一张图片");
      return;
    }
    let newKeyword = axiosData.keyword
      .replace(/，/g, ",")
      .split(",")
      .filter((item) => item.trim());
    axiosData.number = axiosData.number ? axiosData.number : "0";
    axiosData.keyword = JSON.stringify(newKeyword);
    axiosData.imgList = JSON.stringify(imgList);
    axiosData.state = state;
    addItem(axiosData).then((res) => {
      if (res.code === 200) {
        openNotificationWithIcon("success", "成功");
        props.history.replace("/MallList");
      } else if (res.code === 204) {
        openNotificationWithIcon("warning", "服务器错误请稍候再试");
      }
    });
  };

  // 取消
  let outRoute = () => {
    props.history.replace("/MallList");
  };
  return (
    <div className="AddItem">
      <Crumbs CrumbsList={CrumbsList} />
      <div className="additemTitle flex">
        <Icon component={leftIcon} onClick={backUrl} />
        <span className="addTitle">添加积分商品</span>
      </div>
      <div className="additemBox flex">
        <div className="itemLeft">
          <span className="itemLeftId">*</span> 商品名称:
        </div>
        <div className="itemRight">
          <Input
            placeholder="输入商品名称"
            autoComplete="off"
            name="name"
            onChange={changeData}
            value={dataList.name}
          />
        </div>
      </div>
      <div className="additemBox flex">
        <div className="itemLeft">简略标题:</div>
        <div className="itemRight">
          <Input
            placeholder="输入标题"
            autoComplete="off"
            name="title"
            onChange={changeData}
            value={dataList.title}
          />
        </div>
      </div>
      <div className="addItemSort flex">
        <div className="itemBox flex">
          <div className="itemBoxTitle">排序:</div>
          <div>
            <Input
              placeholder="请输入"
              autoComplete="off"
              name="sort"
              onChange={changeData}
              value={dataList.sort}
            />
          </div>
        </div>
        <div className="itemBox flex">
          <div className="itemBoxTitle">库存:</div>
          <div>
            <Input
              placeholder="请输入"
              autoComplete="off"
              name="stock"
              onChange={changeData}
              value={dataList.stock}
            />
          </div>
        </div>
      </div>
      <p className="addPaiSpan">*数字越小越靠前</p>
      <div className="addItemSort flex" style={{ marginTop: "2px" }}>
        <div className="itemBox flex">
          <div className="itemBoxTitle">净重:</div>
          <div>
            <Input
              placeholder="请输入（kg）"
              autoComplete="off"
              name="suttle"
              onChange={changeData}
              value={dataList.suttle}
            />
          </div>
        </div>
        <div className="itemBox flex">
          <div className="itemBoxTitle">品牌:</div>
          <div>
            <Input
              placeholder="请输入"
              autoComplete="off"
              name="brand"
              onChange={changeData}
              value={dataList.brand}
            />
          </div>
        </div>
      </div>
      <div className="additemBox flex">
        <div className="itemLeft">关键词:</div>
        <div className="itemRight">
          <Input
            placeholder="以逗号分开，最多5个"
            autoComplete="off"
            name="keyword"
            onChange={changeData}
            value={dataList.keyword}
          />
        </div>
      </div>
      <div className="additemBox flex">
        <div className="itemLeft">描述:</div>
        <div className="itemRight">
          <Input
            placeholder="请输入商品介绍"
            autoComplete="off"
            name="describes"
            onChange={changeData}
            value={dataList.describes}
          />
        </div>
      </div>
      <div className="addItemSort flex">
        <div className="itemBox flex">
          <div className="itemBoxTitle">药品价格:</div>
          <div>
            <Input
              placeholder="请输入（元）"
              autoComplete="off"
              name="price"
              onChange={changeData}
              value={dataList.price}
            />
          </div>
        </div>
        <div className="itemBox flex">
          <div className="itemBoxTitle">所需积分:</div>
          <div>
            <Input
              placeholder="请输入（积分）"
              autoComplete="off"
              name="points"
              value={dataList.points}
              onChange={changeData}
            />
          </div>
        </div>
      </div>
      <div className="additemBox flex">
        <div className="itemLeft">已出售数量:</div>
        <div className="itemRight flex" style={{ width: "220px" }}>
          <Input
            autoComplete="off"
            name="number"
            onChange={changeData}
            value={dataList.number}
          />
          <Button className="itemBtn">件</Button>
        </div>
      </div>
      <div className="ImageUp flex">
        <div className="ImageUpLeft">图片上传:</div>
        <div className="ImageUpRight">
          <Upload
            accept="image/*"
            action="http://localhost:8888/update/imgupdate"
            listType="picture-card"
            fileList={fileList}
            maxCount={20}
            onPreview={handlePreview}
            onChange={handleChange}
          >
            {fileList.length >= 20 ? null : uploadButton}
          </Upload>
          <Modal
            visible={previewVisible}
            title={previewTitle}
            footer={null}
            onCancel={handleCancel}
          >
            <img alt="example" style={{ width: "100%" }} src={previewImage} />
          </Modal>
        </div>
      </div>
      <div className="subFooter">
        <Button
          type="primary"
          className="sub_shelf"
          icon={<SubIcon />}
          onClick={() => SubIconFun("1")}
        >
          保存并上架
        </Button>
        <Button
          type="primary"
          className="subInventory"
          icon={<SubIcon />}
          onClick={() => SubIconFun("3")}
        >
          保存到库存
        </Button>
        <Button type="primary" className="outBtn" onClick={outRoute}>
          取消
        </Button>
      </div>
    </div>
  );
};

export default AddItem;
